package service

import (
	"bufio"
	"encoding/json"
	"k8sbyhasvc/src/k8sstr"
	"log"
	"net/http"
)

type ServiceMetadata struct {
	Name      string
	Namespace string
}

type ServicePort struct {
	NodePort int
	Protocol string
}

// 如果Type 为 NodePort,这就是需要引出去的服务
type ServiceSpec struct {
	Type  string
	Ports []ServicePort
}

type ServiceObject struct {
	Metadata ServiceMetadata
	Spec     ServiceSpec
}

type Service struct {
	Type   string
	Object ServiceObject
}

type ServiceX struct {
	host      string
	prefix    string
	namespace string
	nsMap     k8sstr.NamespaceMap
}

func (svc *ServiceX) Init(host string, prefix string, namespace string, nsMap k8sstr.NamespaceMap) {
	svc.host = host
	svc.prefix = prefix
	svc.namespace = namespace
	svc.nsMap = nsMap
}

// todo: 检查namespace有没有被删除，如果被删除，就停止这个service
func (svc *ServiceX) Run(ch chan<- Service) {
	resp, err := http.Get(svc.host + "/" + svc.prefix + "/watch/namespaces/" + svc.namespace + "/services")
	if err != nil {
		log.Println("get service :", err)
		return
	}
	defer resp.Body.Close()
	bufrd := bufio.NewReader(resp.Body)

	var service Service

	for {
		buf, _, err := bufrd.ReadLine()
		if err != nil {
			log.Println("readLine ", err)
			return
		}
		json.Unmarshal(buf, &service)
		ch <- service
	}
}
